package com.example.socketchat.service;

import com.example.socketchat.model.ChatMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class ChatMessageService {

    private static final String MESSAGE_KEY_PREFIX = "chat:message:";
    private static final String USER_MESSAGES_KEY_PREFIX = "chat:user:messages:";
    private static final long MESSAGE_EXPIRATION = 24; // 消息保存24小时

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    /**
     * 保存消息到Redis
     */
    public void saveMessage(ChatMessage message) {
        String messageKey = MESSAGE_KEY_PREFIX + message.getId();
        
        // 保存消息本身
        redisTemplate.opsForValue().set(messageKey, message, MESSAGE_EXPIRATION, TimeUnit.HOURS);
        
        // 将消息ID添加到发送者的消息列表
        redisTemplate.opsForList().leftPush(USER_MESSAGES_KEY_PREFIX + message.getSenderId(), message.getId());
        
        // 如果是点对点消息，将消息ID也添加到接收者的消息列表
        if (message.getReceiverId() != null) {
            redisTemplate.opsForList().leftPush(USER_MESSAGES_KEY_PREFIX + message.getReceiverId(), message.getId());
        }
    }
    
    /**
     * 获取用户的所有消息
     */
    public List<Object> getUserMessages(String userId, int start, int end) {
        String userMessagesKey = USER_MESSAGES_KEY_PREFIX + userId;
        List<Object> messageIds = redisTemplate.opsForList().range(userMessagesKey, start, end);
        
        if (messageIds == null || messageIds.isEmpty()) {
            return List.of();
        }
        
        return messageIds.stream()
                .map(id -> redisTemplate.opsForValue().get(MESSAGE_KEY_PREFIX + id))
                .filter(msg -> msg != null)
                .toList();
    }
    
    /**
     * 获取指定ID的消息
     */
    public ChatMessage getMessageById(String messageId) {
        return (ChatMessage) redisTemplate.opsForValue().get(MESSAGE_KEY_PREFIX + messageId);
    }
} 